from flask import Blueprint, request, render_template, url_for
from werkzeug.utils import redirect

from models import House

query_page = Blueprint('query_page', __name__)

"""
实现搜索列表页功能
1.先定义了一个/query的视图函数
2.通过request获取到请求当中的字段的内容
3.使用orm模型查询house表里边的字段
4.使用render_template进行渲染
"""


@query_page.route('/query')
def search_txt_info():
    # 获取地区字段的查询
    if request.args.get('addr'):
        addr = request.args.get('addr')
        result = House.query.filter(House.address == addr).order_by(House.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)
    #House.rooms,先判断rooms，然后获取，然后查询，最后渲染
    if request.args.get('addr'):
        addr = request.args.get('addr')
        result = House.query.filter(House.address == addr).order_by(House.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)
    return redirect(url_for('index_page.index'))

# 当房源标题长度大于15的时候，用省略号替代
def deal_title_over(title):
    if len(title) > 15:
        return title[:15] + '...'
    else:
        return title


# 当房源朝向，交通条件为空的时候，显示暂无信息
def deal_direction(word):
    if len(word) == 0 or word is None:
        return '暂无信息'
    else:
        return word

# 添加过滤器
query_page.add_app_template_filter(deal_title_over, 'dealover')
query_page.add_app_template_filter(deal_direction, 'dealdirection')